﻿using QWManage.DAL;
using QWManage.Forms;
using QWManage.Model;
using QWManage.Utils;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

namespace QWManage
{
    public partial class FrmViewGroups : Form
    {
        private DataTable _dataTable = new DataTable("退群");
        public FrmViewGroups()
        {
            InitializeComponent();
        }

        private void FrmViewGroups_Load(object sender, EventArgs e)
        {
            txtKeywords.KeyUp += TxtKeywords_KeyUp;
            initializeListView();

            cmbRanges.Items.Add("全部数据");
            cmbRanges.Items.Add("已启用的");
            cmbRanges.Items.Add("已屏蔽的");
            cmbRanges.SelectedIndex = 1;
            loadData2ListView();
            cmbRanges.SelectedIndexChanged += CmbRanges_SelectedIndexChanged;
        }

        private void CmbRanges_SelectedIndexChanged(object sender, EventArgs e)
        {
            loadData2ListView(txtKeywords.Text.Trim());
        }

        private void TxtKeywords_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                btnSearch_Click(sender, e);
        }

        private void LvUsers_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            try
            {
                foreach (Control control in this.Controls) control.Enabled = false;
                this.Cursor = Cursors.WaitCursor;
                if (lvUsers.Items.Count == 0) return;
                ColumnHeader ch = lvUsers.Columns[e.Column];
                string orderType = ch.Tag == null ? "" : (string)ch.Tag;
                if (orderType == "" || orderType == "ASC")
                    orderType = "DESC";
                else
                    orderType = "ASC";
                ch.Tag = orderType;
                string fieldName = ch.Name;
                DataTable newTable = _dataTable.Clone();
                DataRow[] drArr = _dataTable.Select("", fieldName + " " + orderType);
                foreach (DataRow dr in drArr)
                {
                    newTable.ImportRow(dr);
                }
                newTable.AcceptChanges();
                _dataTable = newTable;
                lvUsers.VirtualListSize = _dataTable.Rows.Count;
                lvUsers.Invalidate();
            }
            finally
            {
                foreach (Control control in this.Controls) control.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }

        private void initializeListView()
        {
            lvUsers.Items.Clear();
            lvUsers.VirtualMode = true;
            lvUsers.View = View.Details;
            lvUsers.FullRowSelect = true;
            lvUsers.MultiSelect = true;
            lvUsers.Columns.Clear();
            _dataTable.Columns.Clear();


            lvUsers.Columns.Add(new ColumnHeader() { Name = "GroupChatID", Text = "ID", Width = 300 });
            lvUsers.Columns.Add(new ColumnHeader() { Name = "GroupChatName", Text = "名称", Width = 300 });
            lvUsers.Columns.Add(new ColumnHeader() { Name = "Interval", Text = "间隔几分钟定时采集", Width = 150 });
            lvUsers.Columns.Add(new ColumnHeader() { Name = "Disabled", Text = "状态", Width = 100 });

            _dataTable.Columns.Add("GroupChatID", System.Type.GetType("System.String"));
            _dataTable.Columns.Add("GroupChatName", System.Type.GetType("System.String"));
            _dataTable.Columns.Add("Interval", System.Type.GetType("System.String"));
            _dataTable.Columns.Add("Disabled", System.Type.GetType("System.String"));


            // 绑定事件
            lvUsers.RetrieveVirtualItem += ListView_RetrieveVirtualItem;
            lvUsers.ColumnClick += LvUsers_ColumnClick;
            lvUsers.MouseDoubleClick += lvUsers_MouseDoubleClick;
        }

        public void loadDataGroups(string keywords)
        {
            List<GroupInfo> groupInfos = new GroupDAL().GetGroupInfos();
            foreach (GroupInfo group in groupInfos)
            {
                //启用的
                if (cmbRanges.SelectedIndex == 1 && group.Disabled) continue;
                //屏蔽的
                else if (cmbRanges.SelectedIndex == 2 && (!group.Disabled)) continue;

                if (!string.IsNullOrEmpty(keywords))
                {
                    if (
                        (group.ChatID != null && group.ChatID.ToLower().Contains(keywords)) ||
                        (group.Name != null && group.Name.ToLower().Contains(keywords))
                        )
                    {
                        DataRow dr = _dataTable.NewRow();
                        dr["GroupChatID"] = group.ChatID;
                        dr["GroupChatName"] = group.Name;
                        dr["Interval"] = group.Interval.HasValue ? group.Interval.ToString() : "";
                        dr["Disabled"] = group.Disabled ? "屏蔽" : "启用";
                        _dataTable.Rows.Add(dr);
                    }
                }
                else
                {
                    DataRow dr = _dataTable.NewRow();
                    dr["GroupChatID"] = group.ChatID;
                    dr["GroupChatName"] = group.Name;
                    dr["Interval"] = group.Interval.HasValue ? group.Interval.ToString() : "";
                    dr["Disabled"] = group.Disabled ? "屏蔽" : "启用";
                    _dataTable.Rows.Add(dr);
                }
            }
        }

        private void loadData2ListView(string keywords = "")
        {
            try
            {
                foreach (Control control in this.Controls) { control.Enabled = false; }
                this.Cursor = Cursors.WaitCursor;
                _dataTable.Rows.Clear();

                loadDataGroups(keywords);

                lblStatus.Text = $"共 {Common.FormatInt32(_dataTable.Rows.Count)} 条记录";
                lvUsers.VirtualListSize = _dataTable.Rows.Count;
                lvUsers.Invalidate();
            }
            catch (ThreadAbortException) { }
            catch (Exception ex)
            {
                Logs.LogMgr.Log(ex);
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                foreach (Control control in this.Controls) { control.Enabled = true; }
                this.Cursor = Cursors.Default;
            }
        }

        private void ListView_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
        {
            DataRow dr = _dataTable.Rows[e.ItemIndex];
            ListViewItem lvItem = new ListViewItem(dr["GroupChatID"] == DBNull.Value ? "" : dr["GroupChatID"].ToString());
            lvItem.SubItems.Add(dr["GroupChatName"] == DBNull.Value ? "" : dr["GroupChatName"].ToString());
            lvItem.SubItems.Add(dr["Interval"] == DBNull.Value ? "" : dr["Interval"].ToString());
            lvItem.SubItems.Add(dr["Disabled"].ToString());

            if (dr["Disabled"].ToString() == "屏蔽")
                lvItem.ForeColor = Color.Red;
            else
                lvItem.ForeColor = Color.Black;

            e.Item = lvItem;
        }

        private void lvUsers_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ListViewItem item = lvUsers.GetItemAt(e.X, e.Y);
            if (item == null) return;
            DataRow dr = _dataTable.Rows[item.Index];
            string groupid = dr["GroupChatID"].ToString();
            FrmCustomersOfGroup frm = new FrmCustomersOfGroup(groupid);
            frm.ShowDialog();
        }

        private void btnAll_Click(object sender, EventArgs e)
        {
            txtKeywords.Clear();
            loadData2ListView();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            loadData2ListView(txtKeywords.Text.ToLower().Trim());
        }

        private void btnTimer_Click(object sender, EventArgs e)
        {
            if (lvUsers.SelectedIndices.Count == 0)
            {
                Common.MessageBoxWarning("请先选择后再试");
                return;
            }
            FrmGroupTimer frm = new FrmGroupTimer();
            GroupDAL groupDAL = new GroupDAL();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                foreach (var index in lvUsers.SelectedIndices)
                {
                    _dataTable.Rows[(int)index]["Interval"] = frm.Interval.ToString();
                    string chatid = _dataTable.Rows[(int)index]["GroupChatID"].ToString();
                    groupDAL.UpdateGroupInterval(chatid, frm.Interval);
                }
                lvUsers.Invalidate();
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (lvUsers.SelectedIndices.Count == 0)
            {
                Common.MessageBoxWarning("请先选择后再试");
                return;
            }
            GroupDAL groupDAL = new GroupDAL();
            foreach (var index in lvUsers.SelectedIndices)
            {
                _dataTable.Rows[(int)index]["Interval"] = "";
                string chatid = _dataTable.Rows[(int)index]["GroupChatID"].ToString();
                groupDAL.UpdateGroupInterval(chatid, null);
            }
            lvUsers.Invalidate();
        }

        private void btnDisable_Click(object sender, EventArgs e)
        {
            if (lvUsers.SelectedIndices.Count == 0)
            {
                Common.MessageBoxWarning("请先选择后再试");
                return;
            }
            GroupDAL groupDAL = new GroupDAL();
            for (int index = lvUsers.SelectedIndices.Count - 1; index >= 0; index--)
            {
                int rowId = lvUsers.SelectedIndices[index];
                string chatid = _dataTable.Rows[rowId]["GroupChatID"].ToString();
                groupDAL.UpdateGroupStatus(chatid, true);
                if (cmbRanges.SelectedIndex == 1)
                    _dataTable.Rows.RemoveAt(rowId);
                else
                    _dataTable.Rows[rowId]["Disabled"] = "屏蔽";
            }
            lvUsers.VirtualListSize = _dataTable.Rows.Count;
            lvUsers.Invalidate();
            lvUsers.Refresh();
        }

        private void btnEnable_Click(object sender, EventArgs e)
        {
            if (lvUsers.SelectedIndices.Count == 0)
            {
                Common.MessageBoxWarning("请先选择后再试");
                return;
            }
            GroupDAL groupDAL = new GroupDAL();
            for (int index = lvUsers.SelectedIndices.Count - 1; index >= 0; index--)
            {
                int rowId = lvUsers.SelectedIndices[index];
                string chatid = _dataTable.Rows[rowId]["GroupChatID"].ToString();
                groupDAL.UpdateGroupStatus(chatid, false);
                if (cmbRanges.SelectedIndex == 2)
                    _dataTable.Rows.RemoveAt(rowId);
                else
                    _dataTable.Rows[rowId]["Disabled"] = "启用";
            }
            lvUsers.VirtualListSize = _dataTable.Rows.Count;
            lvUsers.Invalidate();
            lvUsers.Refresh();
        }
    }
}
